package com.hava.contentsale.service.impl;

import com.hava.contentsale.dao.ProductVODao;
import com.hava.contentsale.dao.TransactionRecordDao;
import com.hava.contentsale.meta.ProductVO;
import com.hava.contentsale.meta.TransactionRecordPO;
import com.hava.contentsale.meta.UserVO;
import com.hava.contentsale.service.TransactionException;
import com.hava.contentsale.service.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by yanfa on 2016/11/19.
 * 对于交易，发生购买行为
 * 查询product是否存在，并根据product信息，生成交易记录。
 */
@Service
public class TransactionServiceImpl implements TransactionService {

    @Autowired
    ProductVODao productVODao;

    @Autowired
    TransactionRecordDao transactionRecordDao;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void buy(UserVO userVO, long product_id) throws TransactionException {

        if(userVO == null)
            throw new TransactionException("userVO is Empty");
        else if(userVO.getUsertype() != 0)
            throw new TransactionException("userVO not buyer");

        //check and get the product
        ProductVO productVO = this.productVODao.findOneByBuyer(userVO.getId(),product_id);
        if(productVO == null)
            throw new TransactionException("Can not find product or isBuy");
        else if(productVO.getisBuy() != false)
            throw new TransactionException("product isBuy == true");

        //buy
        TransactionRecordPO tr = new TransactionRecordPO();
        tr.setContentId(productVO.getId());
        tr.setPersonId(userVO.getId());
        System.out.println(productVO.getPrice());
        tr.setPrice(productVO.getPrice());
        // 最快的获取时间戳方法
        tr.setTime(System.currentTimeMillis());
        this.transactionRecordDao.create(tr);

//        throw new TransactionException("for test");
//        throwException();
    }

    private void throwException() {
        throw new RuntimeException("Throw Exception");
    }
}
